﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Giraffe.Client.Common;
using Giraffe.Core.Model;
using Microsoft.Practices.Composite.Presentation.Commands;

namespace Giraffe.Client.ConversationModule.Answer
{
    public class AnswerVM: ViewModelBase
    {
        private readonly IConversation _conversation;

        public AnswerVM(IConversation conversation)
        {
            _conversation = conversation;
            SendAnswerCommand = new DelegateCommand<object>(ExecuteSendAnswerCommand, CanExecuteSendAnswerCommand);
        }

        private string _text;
        public string Text
        {
            get
            {
                return _text;
            }
            set
            {
                if (_text == value) return;

                string oldvalue = _text;
                _text = value;
                RisePropertyChanged("Text");
                UpdateCanExecuteIfNeed(oldvalue, value);
            }
        }

        #region Commands

        public DelegateCommand<object> SendAnswerCommand
        {
            get; private set;
        }

        private void ExecuteSendAnswerCommand(object obj)
        {
            _conversation.SendMessage(Text);
            Text = string.Empty;
        }

        private bool CanExecuteSendAnswerCommand(object arg)
        {
            return !string.IsNullOrEmpty(Text);
        }

        private void UpdateCanExecuteIfNeed(string oldText, string newText)
        {
            if ((string.IsNullOrEmpty(oldText) && !string.IsNullOrEmpty(newText))
                || (!string.IsNullOrEmpty(oldText) && string.IsNullOrEmpty(newText)))
            {
                SendAnswerCommand.RaiseCanExecuteChanged();
            }
        }

        #endregion
    }
}
